package com.feng.zshop.backend.service.impl;

import com.feng.zshop.backend.dao.ProductDao;
import com.feng.zshop.backend.dto.ProductDTO;
import com.feng.zshop.backend.service.ProductService;
import com.feng.zshop.common.util.IoUtil;
import com.feng.zshop.common.util.StringUtil;
import com.feng.zshop.model.Product;
import com.feng.zshop.model.ProductType;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author Lee
 * @date 2019/2/17
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductDao productDao;

    /**
     * 保存商品
     *
     * @param productDTO
     */
    @Override
    @Transactional
    public void saveProduct(ProductDTO productDTO) throws FileUploadException {
        // 文件路径
        String filePath = StringUtil.renameFileName(productDTO.getUploadPath(), productDTO.getFileName());

        // 1: 图片上传
//        fileUpload(productDTO.getInputStream(),filePath);
        fileCopy(productDTO.getInputStream(),filePath);

        // 2: 数据库保存图片信息
        saveProductToDataBase(productDTO,filePath);

    }

    public void fileCopy(InputStream inputStream, String filePath) throws FileUploadException {
        try {
            FileUtils.copyInputStreamToFile(inputStream, new File(filePath));
        } catch (IOException e) {
            throw new FileUploadException("图片上传失败");
        }finally {
            IoUtil.release(inputStream);
        }
    }

    private void saveProductToDataBase(ProductDTO productDTO, String filePath) {
        ProductType productType = new ProductType();
        productType.setId(productDTO.getProductTypeId());

        Product product = new Product();
        BeanUtils.copyProperties(productDTO,product);
        product.setImage(filePath);
        product.setProductType(productType);
        productDao.saveProduct(product);
    }

    public void fileUpload(InputStream inputStream, String filePath) throws FileUploadException {
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(filePath);
            byte[] buffer = new byte[1024];
            int len;
            while (((len = inputStream.read(buffer)) != -1)) {
                outputStream.write(buffer, 0, len);
            }
        } catch (IOException e) {
            throw new FileUploadException("文件上传失败");
        }finally {
            IoUtil.release(outputStream);
            IoUtil.release(inputStream);
        }
    }
}
